<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="/Photoloupe.css" />
    <title>Document</title>
  </head>

  <body>
    <div class="box">
      <div class="small">
        <img src="./images/smallpic.jpg" alt="" />
      </div>
      <div class="big"><img src="./images/bigpic.jpg" alt="" /></div>
      <div class="mask"></div>
    </div>
    <script>
      let mask = document.querySelector(".mask");
      let big = document.querySelector(".big");
      let small = document.querySelector(".small");
      let img = document.querySelector(".big img");
      let img1 = document.querySelector(".small  img");
      let fun = function (e) {
        mask.style.top = `${e.clientY - mask.offsetWidth / 2}px`;
        mask.style.left = `${e.clientX - mask.offsetHeight / 2}px`;
        if (parseInt(mask.style.top) < 0) {
          mask.style.top = 0;
        }
        if (parseInt(mask.style.left) < 0) {
          mask.style.left = 0;
        }
        if (parseInt(mask.style.left) > small.clientWidth - mask.clientWidth) {
          // body自己宽度减盒子自己宽度就是不能超出的距离
          mask.style.left = `${small.clientWidth - mask.clientWidth}px`;
        }
        if (parseInt(mask.style.top) > small.clientHeight - mask.clientHeight) {
          mask.style.top = `${small.clientHeight - mask.clientHeight}px`;
        }

        let maskMax = small.offsetWidth - mask.offsetWidth;
        let bingImgMax = img.offsetWidth - big.offsetWidth;

        // 计算得出大图片移动距离
        let bigImgX = (parseInt(mask.style.left) * bingImgMax) / maskMax;
        let bigImgY = (parseInt(mask.style.top) * bingImgMax) / maskMax;

        img.style.left = -bigImgX + "px";
        img.style.top = -bigImgY + "px";
      };
      img1.addEventListener(
        "mouseenter",
        function (e) {
          e.stopPropagation();
          console.log(1);
          mask.style.display = "block";
          big.style.display = "block";
          img1.onmousemove = fun;
        },
        false
      );
      img1.addEventListener(
        "mouseleave",
        function (e) {
          mask.style.display = "none";
          big.style.display = "none";
          img1.onmousemove = null;
        },
        false
      );
    </script>
  </body>
</html>
